NaN
NaN
means Not-A-Number. Let's see examples of NaN
:
NaN
is typically used in conjuction with conditional statements to handle number
scenarios.
Here is a quick example of how to implement NaN
:
info
'1'
is a number, so isNaN()
is false hence returns '1'
.
But 'stringhere'
is clearly not a number hence returns NaN
Here are some operations that return NaN
:
Failed number conversion (as in
Number(undefined)
, or implicitlyMath.abs(undefined)
)Math operation where the result is not real (e.g.
Math.sqrt(-5)
)Indeterminate forms: (
0 * infinity
,1 ** infinity1
, etc)A method/expression whose operand gets coerced to
NaN
: (7 ** NaN
,7 * "word"
)- (
NaN
is contagious)
- (
Cases where an invalid value is represented as a number (
new Date("word".getTime())
)
To test if something is NaN
, one can use Number.isNaN()
, otherwise there is isNaN()
.
tip
Be careful for NaN
values and make sure to check for them in try...catch
methods or throw exceptions.